package com.yunsc.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunsc.common.exception.YunscException;
import com.yunsc.media.service.YunscUploadFileService;
import com.yunsc.product.dao.YunscGoodsCategoryDao;
import com.yunsc.product.dto.GoodsCategoryDTO;
import com.yunsc.product.entity.YunscGoodsCategoryEntity;
import com.yunsc.product.service.YunscGoodsCategoryService;
import com.yunsc.product.vo.GoodsCategoryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


@Service("yunscCategoryService")
public class YunscCategoryServiceImpl extends ServiceImpl<YunscGoodsCategoryDao, YunscGoodsCategoryEntity> implements YunscGoodsCategoryService {

    @Resource
    private YunscUploadFileService uploadFileService;

    @Override
    public List<GoodsCategoryVO> queryGoodsCategory(Integer storeId) {

        LambdaQueryWrapper<YunscGoodsCategoryEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscGoodsCategoryEntity::getStoreId, storeId);
        // 指定字段查询
        List<YunscGoodsCategoryEntity> goodsCategoryList = this.list(lqw);
        // 一级分类
        return goodsCategoryList.stream()
                .filter(category -> category.getParentId() == 0)
                .map(menu -> {
                    GoodsCategoryVO categoryVO = new GoodsCategoryVO();
                    BeanUtils.copyProperties(menu, categoryVO);
                    // 设置一级分类子分类
                    categoryVO.setChildren(getChildren(menu, goodsCategoryList));
                    // 设置一级分类图片
                    categoryVO.setImage(uploadFileService.queryFileById(menu.getImageId()));
                    return categoryVO;
                })
                .sorted(Comparator.comparingInt(GoodsCategoryVO::getSort))
                .collect(Collectors.toList());
    }

    // 递归获取子菜单
    // 递归获取子菜单
    private List<GoodsCategoryVO> getChildren(YunscGoodsCategoryEntity parentCategory, List<YunscGoodsCategoryEntity> list) {
        List<GoodsCategoryVO> children = new ArrayList<>();
        for (YunscGoodsCategoryEntity category : list) {
            if (category.getParentId().equals(parentCategory.getCategoryId())) {
                GoodsCategoryVO categoryVO = new GoodsCategoryVO();
                BeanUtils.copyProperties(category, categoryVO);
                // 递归设置子分类
                categoryVO.setChildren(getChildren(category, list));
                // 设置子分类图片
                categoryVO.setImage(uploadFileService.queryFileById(category.getImageId()));
                children.add(categoryVO);
            }
        }
        // 根据sort字段排序
        children.sort(Comparator.comparingInt(GoodsCategoryVO::getSort));
        return children;
    }

    @Override
    @Transactional
    public void addGoodsCategory(GoodsCategoryDTO categoryDTO, Integer storeId) {
        YunscGoodsCategoryEntity categoryEntity = new YunscGoodsCategoryEntity();
        BeanUtils.copyProperties(categoryDTO.getForm(), categoryEntity);
        categoryEntity.setStoreId(storeId);
        boolean save = this.save(categoryEntity);
        if (!save) {
            throw new YunscException("添加分类失败");
        }
    }

    // 修改分类
    @Override
    @Transactional
    public void editGoodsCategory(GoodsCategoryDTO categoryDTO) {
        Integer categoryId = categoryDTO.getCategoryId();
        YunscGoodsCategoryEntity goodsCategory = this.getById(categoryId);
        if (goodsCategory == null) {
            throw new YunscException("分类不存在");
        }
        BeanUtils.copyProperties(categoryDTO.getForm(), goodsCategory);
        goodsCategory.setCategoryId(categoryId);
        boolean update = this.updateById(goodsCategory);
        if (!update) {
            throw new YunscException("修改分类失败");
        }
    }


    // 删除分类
    @Override
    @Transactional
    public void deleteGoodsCategoryById(Integer categoryId) {
        // 查询分类id是否含有子分类
        int count = this.count(new LambdaQueryWrapper<YunscGoodsCategoryEntity>()
                .eq(YunscGoodsCategoryEntity::getParentId, categoryId));
        if (count > 0) {
            throw new YunscException("该分类下有子分类，不能删除");
        }
        boolean remove = this.removeById(categoryId);
        if (!remove) {
            throw new YunscException("删除分类失败");
        }
    }

    @Override
    @Transactional
    public void updateGoodsCategoryState(GoodsCategoryDTO categoryDTO, Integer storeId) {
        Integer status = categoryDTO.getStatus();
        Integer categoryId = categoryDTO.getCategoryId();
        if (status == null) {
            return;
        }
        if (status == 1) {
            boolean update = this.update(new UpdateWrapper<YunscGoodsCategoryEntity>()
                    .eq("category_id", categoryId)
                    .set("status", 0));
            if (!update) {
                throw new YunscException("修改分类状态失败");
            }
            return;
        }
        if (status == 0) {
            boolean update = this.update(new UpdateWrapper<YunscGoodsCategoryEntity>()
                    .eq("category_id", categoryId)
                    .set("status", 1));
            if (!update) {
                throw new YunscException("修改分类状态失败");
            }
        }
    }


}